package com.xiaojun.whut.aspect;

import com.alibaba.fastjson.JSON;
import com.xiaojun.whut.Entity.SysLog;
import com.xiaojun.whut.Repository.SysLogRepository;
import com.xiaojun.whut.annotation.MyLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.SpringSessionContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @author 鲁佳磊
 * @create 2020-11-05 0:04
 */
@Aspect
@Component
public class SysLogAspect {
    @Autowired
    private SysLogRepository sysLogRepository;

    //定义切点 @Pointcut
    //在注解的位置切入代码
    @Pointcut("@annotation( com.xiaojun.whut.annotation.MyLog)")
    public void logPoinCut() {
    }

    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        System.out.println("切面。。。。。");
        //保存日志
        SysLog sysLog = new SysLog();

        //从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切入点所在的方法
        Method method = signature.getMethod();

        //获取操作
        MyLog myLog = method.getAnnotation(MyLog.class);
        if (myLog != null) {
            String value = myLog.value();
            sysLog.setOperation(value);//保存获取的操作
        }

        //获取请求的类名
        String className = joinPoint.getTarget().getClass().getName();
        //获取请求的方法名
        String methodName = method.getName();
        sysLog.setMethod(className + "." + methodName);

        //请求的参数
        Object[] args = joinPoint.getArgs();
        //将参数所在的数组转换成json
        String params = JSON.toJSONString(args);
        sysLog.setParams(params);

        sysLog.setCreateDate(new Date());
        //获取用户名
        sysLog.setUsername(SecurityContextHolder.getContext().getAuthentication().getName());
        WebAuthenticationDetails details = (WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        sysLog.setIp(details.getRemoteAddress());
        System.out.println("------查看这个一个数据--------");
        System.out.println(SecurityContextHolder.getContext().getAuthentication().getName());
        System.out.println(details.getRemoteAddress());
        System.out.println("--------------");

        sysLogRepository.save(sysLog);
    }

}
